package com.btex.app;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.verificationsdk.ui.IActivityCallback;
import com.alibaba.verificationsdk.ui.VerifyActivity;
import com.alibaba.verificationsdk.ui.VerifyType;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.LogUtil;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RegistActivity extends BaseActivity {
    private static final java.lang.String TAG = "RegistActivity";
    private TimeCount time;
    private EditText etEmailMobile;
    private EditText etPsw;
    private LinearLayout llIvCode;
    private EditText etIvCode;
    private ImageView ivCode;
    private EditText etCode;
    private Button btnGetCode;
    private Button btnRegistNext;
    private PreferencesCookieStore cookieStore;
    private ImageLoader imageLoader;
    private MicroAVLIDialog mMicroAVLIDialog;

    private void assignViews() {
        etEmailMobile = (EditText) findViewById(R.id.etEmailMobile);
        etPsw = (EditText) findViewById(R.id.etPsw);
        llIvCode = (LinearLayout) findViewById(R.id.ll_ivCode);
        etIvCode = (EditText) findViewById(R.id.et_ivCode);
        ivCode = (ImageView) findViewById(R.id.iv_code);
        etCode = (EditText) findViewById(R.id.etCode);
        btnGetCode = (Button) findViewById(R.id.btnGetCode);
        btnRegistNext = (Button) findViewById(R.id.btnRegistNext);

        cookieStore = CookieTool.getCookieStore(cxt, sp);

        etCode.addTextChangedListener(new MyWatcher());
        etIvCode.addTextChangedListener(new MyWatcher());
        etEmailMobile.addTextChangedListener(new MyWatcher());
        etPsw.addTextChangedListener(new MyWatcher());

        initData();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);

        mMicroAVLIDialog = new MicroAVLIDialog(this);
        assignViews();

    }


    @Override
    public void setData() {
        tv_title.setText(R.string.regist);
        time = new TimeCount(60000, 1000);
        imageLoader = ImageLoader.getInstance();
        String string = sp.getString(Config.COOKIE, null);
        imageLoader.displayImage(Config.URL_CHECK_PIC + string, ivCode);
        //点击下一步
        btnRegistNext.setOnClickListener(this);
        //获取验证码
        btnGetCode.setOnClickListener(this);
        ivCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btnGetCode:

                if (TextUtils.isEmpty(etEmailMobile.getText())) {

                    Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.email_mobile_cant_be_empty));

//                    SnackbarShow(getString(R.string.email_mobile_cant_be_empty));
                } else {
                    mMicroAVLIDialog.show();
                    getCode(etEmailMobile.getText().toString());  //获取验证码
                }

                break;
            case R.id.btnRegistNext:

//                mMicroAVLIDialog.show();
//                toRegist(etEmailMobile.getText().toString(), etPsw.getText().toString(), etCode.getText().toString());

                callSDKDoVerification(VerifyType.NOCAPTCHA, null);

                break;
            case R.id.iv_code:
//                imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
                imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
            default:
                break;
        }
    }

    /**
     * 注册 校验
     */
    private void toRegist(String acount, String psw, String code, String sessionID) {

        String isEngilshs;

        boolean isEngilsh = sp.getBoolean("isEngilsh", false);
        if (isEngilsh) {
            isEngilshs = "en";
        } else {
            isEngilshs = "zh_cn";
        }


        sp.putString(Config.KEY_USER_ACCOUNT, acount);


        if (TextUtils.isEmpty(acount)) {
//            Toast.makeText(RegistActivity.this, R.string.input_counter, Toast.LENGTH_SHORT).show();
            Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.input_counter));
//            SnackbarShow(getString(R.string.input_counter));
            mMicroAVLIDialog.dismiss();
            return;
        }


        if (TextUtils.isEmpty(psw)) {
//            Toast.makeText(RegistActivity.this, R.string.input_counter, Toast.LENGTH_SHORT).show();
            Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.input_mima));
//            SnackbarShow(getString(R.string.input_mima));
            mMicroAVLIDialog.dismiss();
            return;
        }


//        if (TextUtils.isEmpty(code)) {
//            SnackbarShow("请输入图形验证码");
////            Toast.makeText(RegistActivity.this, R.string.code_is_empty, Toast.LENGTH_SHORT).show();
//            mMicroAVLIDialog.dismiss();
//            return;
//        }

        if (TextUtils.isEmpty(code)) {

            Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.code_is_empty));
//            SnackbarShow(getString(R.string.code_is_empty));
//            Toast.makeText(RegistActivity.this, R.string.code_is_empty, Toast.LENGTH_SHORT).show();
            mMicroAVLIDialog.dismiss();
            return;
        }

        if (TextUtils.isEmpty(sessionID)) {
            Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.an_quan));
//            SnackbarShow(getString(R.string.an_quan));
//            Toast.makeText(RegistActivity.this, R.string.code_is_empty, Toast.LENGTH_SHORT).show();
            mMicroAVLIDialog.dismiss();
            return;
        }


        RequestParams params = new RequestParams();
        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        params.addHeader("app-version", Config.VERSION);
        params.addHeader("my-client", "android");
        params.addQueryStringParameter(Config.KEY_USER_ACCOUNT, acount);
        params.addQueryStringParameter(Config.KEY_USER_PSW, psw);
//        params.addQueryStringParameter(Config.KEY_CHECK_PIC, imgCode);
        params.addQueryStringParameter(Config.KEY_CODE, code);
        params.addQueryStringParameter("lang", isEngilshs);
        params.addQueryStringParameter("code_sessionid", sessionID);
        params.addQueryStringParameter("code_scene", "register");
//        params.addQueryStringParameter("origin_channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));


        HashMap<String, String> stringStringHashMap = new HashMap<>();

        stringStringHashMap.put("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        stringStringHashMap.put(Config.KEY_USER_ACCOUNT, acount);
        stringStringHashMap.put(Config.KEY_USER_PSW, psw);
        stringStringHashMap.put(Config.KEY_CODE, code);
        stringStringHashMap.put("lang", isEngilshs);
        stringStringHashMap.put("code_sessionid", sessionID);
        stringStringHashMap.put("code_scene", "register");

        OkGo.<String>post(Config.URL_REGISTER).params(stringStringHashMap).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
//                LogUtil.i(TAG, "注册结果：" + responseInfo.result.toString());
                mMicroAVLIDialog.dismiss();
                String result = response.body();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        sp.putString(Config.TOKEN, jsonObject.getJSONObject(Config.KEY_DATA).getString(Config.TOKEN));

                        Intent i = new Intent(cxt, TradeRegistPsw.class);
                        startActivity(i);
                        finish();
                    } else if ("-1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        String string = sp.getString(Config.COOKIE, null);
                        imageLoader.displayImage(Config.URL_CHECK_PIC + string, ivCode);
                        etIvCode.setText("");
//                        Toast.makeText(cxt, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                        Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), jsonObject.getString("info"));

//                        SnackbarShow(jsonObject.getString("info"));
                    }

                } catch (JSONException e) {

                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Toast.makeText(RegistActivity.this, R.string.fail_check_code, Toast.LENGTH_SHORT).show();
            }
        });

//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.URL_REGISTER, params, new RequestCallBack<Object>() {
//            @Override
//            public void onSuccess(ResponseInfo<Object> responseInfo) {
//                LogUtil.i(TAG, "注册结果：" + responseInfo.result.toString());
//                mMicroAVLIDialog.dismiss();
//                String result = responseInfo.result.toString();
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                        sp.putString(Config.TOKEN, jsonObject.getJSONObject(Config.KEY_DATA).getString(Config.TOKEN));
//
//                        Intent i = new Intent(cxt, TradeRegistPsw.class);
//                        startActivity(i);
//                        finish();
//                    } else if ("-1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                        String string = sp.getString(Config.COOKIE, null);
//                        imageLoader.displayImage(Config.URL_CHECK_PIC + string, ivCode);
//                        etIvCode.setText("");
////                        Toast.makeText(cxt, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
//                        Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), jsonObject.getString("info"));
//
////                        SnackbarShow(jsonObject.getString("info"));
//                    }
//
//                } catch (JSONException e) {
//
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//                Toast.makeText(RegistActivity.this, R.string.fail_check_code, Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    /**
     * 获取验证码
     */
    private void getCode(String acount) {
        String isEngilshs;

        boolean isEngilsh = sp.getBoolean("isEngilsh", false);
        if (isEngilsh) {
            isEngilshs = "en";
        } else {
            isEngilshs = "zh_cn";
        }

        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(this);
        String cookies = sharedPreferences.getString(Config.COOKIE, null);
        cookieStore = CookieTool.getCookieStore(cxt, sharedPreferences);
        RequestParams params = new RequestParams();
        params.setHeader(Config.TOKEN, token);
        params.addQueryStringParameter(Config.KEY_USER_ACCOUNT, acount);
        params.addQueryStringParameter(Config.TOKEN, cookies);
        params.addQueryStringParameter("lang", isEngilshs);


        OkGo.<String>post(Config.URL_GET_REGIST_CODE).params(Config.TOKEN, token).params(Config.KEY_USER_ACCOUNT, acount)
                .params(Config.TOKEN, cookies)
                .params("lang", isEngilshs)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        Log.i("eofkpwkefpwokefpw", result);

                        mMicroAVLIDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                                time.start();  //启动定时器
                                Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.bg_green), getString(R.string.suc_get_code));
//                        SnackbarShow(getString(R.string.suc_get_code));
                            } else {
                                Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.fail_get_code));
//                        SnackbarShow(getString(R.string.suc_get_code));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.fail_get_code));
                    }
                });


//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.URL_GET_REGIST_CODE, params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                String result = responseInfo.result.toString();
//                Log.i("eofkpwkefpwokefpw", result);
//
//                mMicroAVLIDialog.dismiss();
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                        time.start();  //启动定时器
//                        Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.bg_green), getString(R.string.suc_get_code));
////                        SnackbarShow(getString(R.string.suc_get_code));
//                    } else {
//                        Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.fail_get_code));
////                        SnackbarShow(getString(R.string.suc_get_code));
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
////                SnackbarShow(getString(R.string.fail_get_code));
//                Util.showSnachBar(RegistActivity.this, getResources().getColor(R.color.red), getString(R.string.fail_get_code));
//            }
//        });
    }

    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            btnGetCode.setClickable(true);
            btnGetCode.setText("重新发送");
            btnGetCode.setTextColor(getResources().getColor(R.color.app_color));
            btnGetCode.setBackgroundResource(R.drawable.text_view_boder);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btnGetCode.setClickable(false);
            btnGetCode.setText("重新发送(" + millisUntilFinished / 1000 + ")");
            btnGetCode.setTextColor(getResources().getColor(R.color.tv_hint_gray));
//            btnGetCode.setBackgroundResource(R.drawable.bg_et_gray);
            btnGetCode.setBackgroundResource(R.drawable.text_view_boder);
        }

    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            if (!TextUtils.isEmpty(etEmailMobile.getText()) && !TextUtils.isEmpty(etPsw.getText()) && !TextUtils.isEmpty(etIvCode.getText()) && !TextUtils.isEmpty(etCode.getText())) {
                btnRegistNext.setBackgroundResource(R.drawable.selector_btn_app_color);
                btnRegistNext.setClickable(true);
                btnRegistNext.setTextColor(getResources().getColor(R.color.white));
            } else {
                btnRegistNext.setBackgroundResource(R.drawable.selector_btn_app_color);
                btnRegistNext.setClickable(true);
                btnRegistNext.setTextColor(getResources().getColor(R.color.white));
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == 4) {
            String sessionID = data.getStringExtra("sessionID");

            toRegist(etEmailMobile.getText().toString(), etPsw.getText().toString(), etCode.getText().toString(), sessionID);
        }
    }


    /**
     * 验签主调用功能函数
     *
     * @param selectedIndex 验证类型，目前只支持 滑动验证
     * @param data          验证需要传入的数据，默认传 null
     */
    public void callSDKDoVerification(VerifyType selectedIndex, String data) {
        if (data == null) {
            VerifyActivity.startSimpleVerifyUI(RegistActivity.this, selectedIndex, "0335", null, new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {


                }

                @Override
                public void onResult(int retInt, Map code) {

                    RegistActivity.this.verifyDidFinishedWithResult(retInt, code);
                }
            });
        } else {
            Map<String, String> params = new HashMap<>();
            //设置params，目前只需设置 VerifyActivity.APP_DATA
            params.put(VerifyActivity.APP_DATA, data);
            VerifyActivity.startVerifyUI(RegistActivity.this, params, selectedIndex, "0335", null, new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {

                }

                @Override
                public void onResult(int retInt, Map code) {
                    RegistActivity.this.verifyDidFinishedWithResult(retInt, code);
                }
            });
        }
    }


    /**
     * 验签回调功能函数
     *
     * @param retInt 返回码
     * @param code   返回内容
     */
    public void verifyDidFinishedWithResult(int retInt, Map code) {
        switch (retInt) {
            case VerifyActivity.VERIFY_SUCC:

                String sessionID = (String) code.get("sessionID");
                mMicroAVLIDialog.show();
                toRegist(etEmailMobile.getText().toString(), etPsw.getText().toString(), etCode.getText().toString(), sessionID);

                break;

            case VerifyActivity.VERIFY_FAILED:

                VerifyActivity.finishVerifyUI();
                break;
        }
    }

}
